package com.taichuan.keysupport.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2019/12/19
 */
public abstract class TcKeyListView extends ListView {
    protected String TAG = this.getClass().getSimpleName();

    /**
     * 定义一个变量用于表示ListView 是否 不处于 触摸模式
     */
    protected boolean setNotouchMode;

    public TcKeyListView(Context context) {
        super(context);
    }

    public TcKeyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TcKeyListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void init() {
        setOnKeyListener(setTcKeyListener());
        setOnFocusChangeListener(mFocusChangeListener);
    }

    /**
     * 定义一个ListView焦点变化监听对象
     */
    private final OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            Log.i(TAG, "onFocusChange: 焦点发生改变的view为：  " + v.getClass().getSimpleName() + "  hasFocus：  " + hasFocus);
            if (hasFocus) {
                if (getCount() > 0) {
//                    setNotouchMode = true;
                }
            }

        }
    };

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocus();
    }

    public void requestOrClearFocus(boolean isRequest){
        if (isRequest){
            setFocusable(true);
            setFocusableInTouchMode(true);
            requestFocus();
        }else {
            clearFocus();
            setFocusable(false);
            setFocusableInTouchMode(false);
        }
    }

    @Override
    public boolean isInTouchMode() {
        if (setNotouchMode) {
            return false;
        } else {
            return super.isInTouchMode();
        }
    }

    @Override
    public void setSelectionFromTop(int position, int y) {
        super.setSelectionFromTop(position, y);
        Log.i(TAG, "setSelectionFromTop: position为： " + position + "  y:  " + y);
        setNotouchMode = false;
    }

    /**
     * 定义一个抽象方法用于创建ListView的按键监听事件回调，具体实现交由子类完成
     * @return
     */
    protected abstract OnKeyListener setTcKeyListener();
}
